package dyyx;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.InputStream;

public class Utils {

	private static final int BUF_SIZE = 512;

	public static final String UTF8 = "utf8";
	
	
	public static void doSleep(long time){
		if(time<=0){
			return;
		}
		try{
			Thread.sleep(time);
		}catch(Throwable e){
			
		}
	}
	
	public static int getInt(String str){
		return getInt(str,0);
	}

	
	public static int getInt(String str,int def){
		if(str==null || str.isEmpty()){
			return def;
		}	
		try{
			return Integer.parseInt(str);	
		}catch(Throwable e){
			return def;
		}
	}
	
	public static int getSysPropInt(String name,int def){
		String str = System.getProperty(name);
		return getInt(str,def);
	}
	
	public static int getSysPropInt(String name){
		return getSysPropInt(name,0);
	}

	
	

	public static String readFromClassPath(String name, String charset) throws Exception {
		InputStream inputStream = null;

		try {
			inputStream = Utils.class.getClassLoader().getResourceAsStream(name);
			if(inputStream==null){
				inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(name);
			}
			
			if(inputStream==null){
				throw new Exception("resource not found,"+name);
			}
			
			
			byte[] bytes = toBytes(inputStream);
			if (charset == null) {
				charset = UTF8;
			}

			return new String(bytes, charset);
		} finally {
			close(inputStream);
		}
	}

	private static byte[] toBytes(InputStream is) throws Exception {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buf = new byte[BUF_SIZE];
		int len = 0;
		while ((len = is.read(buf)) != -1) {
			if (len > 0) {
				bos.write(buf, 0, len);
			}
		}
		return bos.toByteArray();
	}

	public static void close(Closeable obj) {
		if (obj == null) {
			return;
		}
		try {
			obj.close();
		} catch (Throwable e) {
			// 
		}
	}

}
